package slices

// values插入到slice的index位置,原index及其后面的数据依次后移的结果. 若index位置错误,直接添加到末尾
func Inserts[TYPE any](slice []TYPE, index int, values ...TYPE) (newSlice []TYPE) {
	if index < 0 || index > len(slice) {
		index = len(slice)
	}
	newSlice = make([]TYPE, 0, len(slice)+len(values))
	newSlice = append(newSlice, slice[:index]...)
	newSlice = append(newSlice, values...)
	return append(newSlice, slice[index:]...)
}

// values追加到slice的末尾的结果.相当于Inserts(slice, -1, values...)
func Append[TYPE any](slice []TYPE, values ...TYPE) (newSlice []TYPE) {
	return Inserts(slice, -1, values...)
}

// values插入到slice的前端的结果.相当于Inserts(slice, 0, values...)
func Prepend[TYPE any](slice []TYPE, values ...TYPE) (newSlice []TYPE) {
	return Inserts(slice, 0, values...)
}

// 创建一个新的slice
func New[TYPE any](values ...TYPE) (newSlice []TYPE) {
	newSlice = make([]TYPE, len(values))
	copy(newSlice, values)
	return
}

// 深拷贝出一个新的slice,同New(slice...)
func Copy[TYPE any](slice []TYPE) (newSlice []TYPE) {
	return New(slice...)
}

// 删除slice中所有value的结果
func Remove[TYPE comparable](slice []TYPE, values ...TYPE) (newSlice []TYPE) {
	newSlice = Copy(slice)
	for _, value := range values {
		curOld, curNew := 0, 0
		for ; curOld < len(newSlice); curOld++ {
			if newSlice[curOld] == value {
				continue
			}
			newSlice[curNew] = newSlice[curOld]
			curNew++
		}
		newSlice = newSlice[:curNew]
	}
	return
}

// slice中移除from开始到length长度的数据的结果,from和length错误会返回结果和原slice相等
func Cut[TYPE comparable](slice []TYPE, from, length int) (newSlice []TYPE) {
	newSlice = Copy(slice)
	if length <= 0 {
		return
	}
	if from < 0 {
		from = 0
	}
	if from > len(slice) {
		from = len(slice)
	}
	to := from + length
	if to > len(slice) {
		to = len(slice)
	}
	return append(newSlice[:from], newSlice[to:]...)
}

// 返回value在Index中出现的位置,不存在返回-1
func Index[TYPE comparable](slice []TYPE, value TYPE) int {
	for i := 0; i < len(slice); i++ {
		if slice[i] == value {
			return i
		}
	}
	return -1
}

func sort[TYPE comparable](slice []TYPE, swap func(front, back TYPE) bool) {
	lenght := len(slice)
	if lenght < 2 {
		return
	}
	cur := 0
	for i := 1; i < lenght; i++ {
		if swap(slice[cur], slice[i]) {
			slice[cur], cur, slice[i] = slice[i], i, slice[cur]
		}
	}
	sort(slice[:cur], swap)
	sort(slice[cur+1:], swap)
}

// 根据swap快速度排序,若swap回调函数的front应该在back后面返回true.
func Sort[TYPE comparable](slice []TYPE, swap func(front, back TYPE) bool) (newSlice []TYPE) {
	newSlice = Copy(slice)
	sort(newSlice, swap)
	return
}

// 返回两个slice的交集
func Unite[TYPE comparable](slice1 []TYPE, slice2 []TYPE) (unite []TYPE) {
	for i1 := 0; i1 < len(slice1); i1++ {
		for i2 := 0; i2 < len(slice2); i2++ {
			if slice1[i1] == slice2[i2] {
				unite = append(unite, slice1[i1])
			}
		}
	}
	return
}
